package com.sloth.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.AlipayResponse;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.sloth.pojo.*;
import com.sloth.service.*;
import com.sloth.util.AlipayConfig;
import com.sloth.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("ali")
public class AliPayController {
//    @Autowired
//    private OrderService orderService;

    @Autowired
    private PlaceAnOrderService placeAnOrderService;

    @Autowired
    private OrderDetailService orderDetailService;

    @Autowired
    private MyOrderService myOrderService;

    @Autowired
    private FlowService flowService;

    @Autowired
    private ProductService productService;

    // 商品名字、订单编号、订单金额

    // 1. 支付：调用支付宝支付
    @PostMapping(value = "pay" ,produces = "text/html;charset=utf-8")
    @ResponseBody
    public String pay(Integer newMyOrderId,HttpServletRequest request){

        // 获得订单中所有商品拼接过的名称（String 类型的字符串）
        ALiPayMyOrderProductNameAndCount byMyOrderIdForProNames = placeAnOrderService.getByMyOrderIdForProNames(newMyOrderId);

        //(1)初始化AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
        //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://localhost:8080/shulanmiaosha/ali/alipayReturnNotice");
//        alipayRequest.setReturnUrl(AlipayConfig.return_url); // 同步请求支付
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url); // 异步请求支付


        //(3)支付请求中的订单信息 --- alirequest  context
        String out_trade_no = byMyOrderIdForProNames.getOrderNo().toString();  // 订单编号
        System.out.println("订单编号： " + out_trade_no);
        String total_amount = byMyOrderIdForProNames.getOrderTotalPrice().toString();  // 订单中商品总价格
        System.out.println("订单总价格： " + total_amount);
        String subject = byMyOrderIdForProNames.getProductsName();  // 订单中商品名称
        System.out.println("订单中商品名称： " + subject);
        String body = "";
        String timeout_express = "10m";    // 该笔订单允许的最晚付款时间，逾期将关闭交易。取值范围：1m～15d。m-分钟，h-小时，d-天，1c-当天（1c-当天的情况下，无论交易何时创建，都在0点关闭）。 该参数数值不接受小数点， 如 1.5h，可转换为 90m。

        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

        String payResult = null;
        try {
            AlipayResponse alipayResponse =  alipayClient.pageExecute(alipayRequest);

            System.out.println("pay code:"+ alipayResponse.getCode());
            System.out.println("pay getSubCode:"+ alipayResponse.getSubCode());
            System.out.println("pay getMsg:"+ alipayResponse.getMsg());
            System.out.println("pay isSuccess:"+ alipayResponse.isSuccess());
            payResult =  alipayResponse.getBody();// getBody() 支付后，支付宝返回的支付的信息
            System.out.println("支付宝返回的支付的信息：" + payResult);
            System.out.println("支付宝返回的 Params 的信息： " + alipayResponse.getParams());
            System.out.println();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        System.out.println("跳转到支付宝");
        return  payResult;
    };

    // 同步请求
    // 支付后的 获得 支付宝的信息 payResult --->request
    @RequestMapping("alipayReturnNotice")
    @ResponseBody
    public ModelAndView returnNotice(HttpServletRequest request,HttpServletResponse response,Customer customer){
        System.out.println("同步返回页面操作。。。。。");

        ModelAndView mav = new ModelAndView();

        Map<String,String[]> map= request.getParameterMap();
        System.out.println(">>>>>支付后的 获得 支付宝的信息 " + map.toString());
        Iterator<Map.Entry<String, String[]>> iterator = map.entrySet().iterator();
        while (iterator.hasNext()){
            Map.Entry<String, String[]> next = iterator.next();
            System.out.println(next.getKey());
            System.out.println(next.getValue()[0]);
        }

        // 获得支付金额
        String total_amount = map.get("total_amount")[0];
        Double flowAmount = Double.parseDouble(total_amount);

        // 支付宝的支付时间
        String timestamp = map.get("timestamp")[0];
        System.out.println("支付宝支付时间： " + timestamp);

        Date date = DateUtil.stringToDate(timestamp, DateUtil.DATE_FORMAT_YMDHMS);

        // 已经登录的用户id
        Integer customerId = 0 ;

        customerId = customer.getCustId();

        /*while (attributeNames.hasMoreElements()){
            String s = attributeNames.nextElement().toString();
            Customer customer = (Customer)session.getAttribute(s);
            customerId = customer.getCustId();
        }*/

        // 通过订单编号，获取到订单id，再通过 订单id 关联到的订单详情，生成每一条订单详情对应的流水信息
        String strMyOrderNO = map.get("out_trade_no")[0];  // 订单编号
        Long myOrderNO = Long.parseLong(strMyOrderNO);

        // 在订单表中查询这个订单的信息
        Myorder myorder = myOrderService.getByMyOrderNO(myOrderNO);

        // 付款之后，修改订单的状态：已付款：1
        myorder.setOrderStates(1);
        Integer integer1 = myOrderService.updateMyOrderStatue(myorder);

        // 通过 订单id 在订单详情表中查询出属于这个 订单id 的所有订单详情信息
        List<OrderDetails> byMyOrderId = orderDetailService.getByMyOrderId(myorder.getOrderId());

        // 遍历得到的订单详情信息，每一条订单详情记录生成一条对应的流水记录，流水表中的金额是该订单详情表中的商品单价与对应的商品的价格的积
        // 把订单中的订单详情中的状态改为已付款
        for (OrderDetails orderDetails : byMyOrderId){

            orderDetails.setOdStates(1);

            // 调用支付宝之后要把订单详情中的支付时间加上去
            orderDetails.setOdPayDate(date);

            // 调用OrderService层进行就该信息
            orderDetailService.updateMyOrderDetail(orderDetails);

            // 获得订单详情记录中的商品id，在商品表中查询商品价格
            Double productPrice = productService.getByOrderDetailsProductId(orderDetails.getProId());
            Double flowPrice = productPrice * orderDetails.getOdProCount();

            // 生成流水信息
            Flow flow = new Flow();
            flow.setFlowNum(new Date().getTime()); // 流水编号
            flow.setCustId(customerId);  // 用户id
            flow.setOrderId(orderDetails.getOrderId());  // 订单id
            flow.setFlowPaytime(date);  // 支付时间
            flow.setFlowCost(flowPrice);  // 支付金额
            flow.setState(0);
            // 订单中的每个订单详情都要关联一个流水表，所以流水表中第一个other作为订单详情id关联上
            flow.setOthers1(orderDetails.getOdDetailsId().toString());

            // 向数据库中添加流水信息
            Integer integer = flowService.saveFlow(flow);
            System.out.println("流水信息是否添加成功？ " + integer);

        }
        // 订单编号
        mav.addObject("myOrderId",myorder.getOrderNo());
        // 支付宝单号
        mav.addObject("trade_no",map.get("trade_no")[0]);
        // 实付金额
        mav.addObject("total_amount",map.get("total_amount")[0]);
        // 支付时间
        mav.addObject("timestamp",map.get("timestamp")[0]);

        mav.setViewName("order/pay_syccess");

        return mav;
    }

    @GetMapping("alipayNotifyNotice")
    @ResponseBody
    public String notifyNotice(HttpServletRequest request,HttpServletResponse response){
        System.out.println("异步返回页面操作。。。。。");
        Map<String,String[]> map= request.getParameterMap();
        System.out.println("支付后的 获得 支付宝的信息 " + map);
        return "alipaySuccess";
    }

}